package com.think.admin.oauth.handle;

import com.think.common.utils.JacksonUtils;
import com.think.common.utils.ResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token 异常
 *
 * @author xieWenJie
 * @date 2018年12月17日
 */
@Component
public class OauthAuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    /**
     * 错误返回特征值
     */
    private final String NOT_TOKEN = "Full authentication is required to access this resource";
    private final String INVALID = "Invalid access token";

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        String msg;
        if (NOT_TOKEN.equals(authException.getMessage())) {
            msg = "请求失败：请先登录";
        } else if (-1 != authException.getMessage().indexOf(INVALID)) {
            msg = "请求失败：token无效";
        } else {
            msg = authException.getMessage();
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json;charset=UTF-8");
        authException.getMessage();
        response.getWriter().write(
                JacksonUtils.toJson(new ResultUtil(HttpStatus.UNAUTHORIZED, msg)));
    }
}
